package com.chinaunicom.emergency.service;

import com.chinaunicom.emergency.action.TokenExtendAction;
import com.chinaunicom.emergency.model.Role;
import com.chinaunicom.emergency.model.Rolepermissions;
import com.chinaunicom.emergency.util.JPAUtil;
import com.chinaunicom.emergency.repository.RolePermissionsRepository;
import com.chinaunicom.emergency.repository.RoleRepository;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * @Author liliang
 * @Date 2019/12/17 15:37
 * @Version 1.0
 */
@Service
@Log4j2
public class RoleService {
    @Autowired
    private RoleRepository roleRepository;
    @Autowired
    private TokenExtendAction authClient;
    @Autowired
    RolePermissionsRepository rolePermissionsRepository;

    @Transactional(rollbackFor = Exception.class)
    public void setPermission(String roleId, List<String> permissionList, String currUserId) throws Exception{
        authClient.revokeToken(null,roleId,null);
        List<Rolepermissions> list = new ArrayList();
        rolePermissionsRepository.deleteByRoleId(roleId);
        for(String permissionId : permissionList){
            Rolepermissions rolePer = new Rolepermissions();
            rolePer.setRoleId(roleId);
            rolePer.setIsSoftDel(0);
            rolePer.setPermissionsId(permissionId);
            rolePer.setCreateTime(new Date());
            rolePer.setCreateBy(currUserId);
            list.add(rolePer);
        }
        rolePermissionsRepository.saveAll(list);
    }

    public Specification findPageByCondition(Map para){
        return new Specification<Role>() {

            @Override
            public Predicate toPredicate(Root<Role> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<>();

                JPAUtil.like(list,cb,root,"roleName",para);
                JPAUtil.equal(list,cb,root,"isSoftDel",para);
                return cb.and(list.toArray(new Predicate[list.size()]));
            }
        };
    }


    @Transactional(rollbackFor = Exception.class)
    public void delete(Role role) {
        roleRepository.save(role);
        rolePermissionsRepository.deleteByRoleId(role.getPid());
    }
}
